from flask import render_template, redirect, url_for, abort, flash, request, \
    current_app, make_response, send_from_directory, session
from sqlalchemy import or_
from . import main
from .. import db, observer, config
from ..models.tools import Tool
from .forms import SearchForm
from ..observer.controllers import tools_init
from ..observer.observer_api import create_observer
import os.path


@main.route('/', methods=['GET', 'POST'])
def index():
    global observer
    if not observer:
        observer = create_observer('default')
        observer.start()
        db.create_all()
        tools_init(current_app)
    form = SearchForm()
    if form.is_submitted():
        session['search_data'] = form.search.data
    if 'search_data' in session and session['search_data']:
        tools = Tool.query.filter(
            or_(Tool.name.contains(session['search_data']), Tool.description.contains(session['search_data']))).all()
    else:
        tools = Tool.query.all()
    labels = ["工具名", "描述", "当前版本", "下载"]

    def _get_latest(s):
        a = s.versions.filter_by(is_latest=True).first()
        return a.version if a else ""

    def _get_href(s):
        a = s.versions.filter_by(is_latest=True).first()
        if a:
            file_path = os.path.join(s.path, a.tool_name)
            if not os.path.exists(file_path):
                return "{}文件不存在".format(a.tool_name)
            return '<a href="/download/{0}" title = "下载">下载</a>'.format(s.id)
        else:
            return ""

    content = [[tool.name, tool.description, _get_latest(tool) or "未知", _get_href(tool) or "无可下载"] for tool in tools]
    return render_template('index.html', form=form, labels=labels, content=content)


@main.route('/download/<int:id>')
def download(id):
    tool = Tool.query.filter_by(id=id).first()
    if tool:
        version = tool.versions.filter_by(is_latest=True).first()
        file_path = os.path.join(tool.path, version.tool_name)
        if not os.path.exists(file_path):
            abort(404)
        directory = os.path.dirname(file_path)
        filename = os.path.basename(file_path)
        response = make_response(send_from_directory(directory, filename, as_attachment=True))
        response.headers["Content-Disposition"] = "attachment; filename={}".format(filename.encode().decode('latin-1'))
    else:
        abort(404)
    return response

#
# @main.route('/jumpftp/<int:id>')
# def jumpftp(id):
#     href = query_ftp(id)
#     return render_template(href)
#
#
# @main.route('/jumpgitlab/<int:id>')
# def jumpgitlab(id):
#     href = query_gitlab(id)
#     return render_template(href)
